package com.wgh.product.controller;

import com.wgh.common.vo.PageResult;
import com.wgh.common.vo.Result;
import com.wgh.product.converter.ProductConverter;
import com.wgh.product.dto.ProductDTO;
import com.wgh.product.entity.shop.Product;
import com.wgh.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 商品Controller
 * 提供商品相关的RESTful API接口
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;
    
    @Autowired
    private ProductConverter productConverter;

    /**
     * 分页查询商品列表
     */
    @GetMapping("/page")
    public Result<PageResult<ProductDTO>> getProductPage(
            @RequestParam Map<String, Object> params,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageResult<Product> productPage = productService.getProductPage(params, pageNum, pageSize);
            List<ProductDTO> productDTOs = productConverter.toDTOList(productPage.getList());
            
            PageResult<ProductDTO> dtoPage = new PageResult<>();
            dtoPage.setList(productDTOs);
            dtoPage.setTotal(productPage.getTotal());
            dtoPage.setPageNum(productPage.getPageNum());
            dtoPage.setPageSize(productPage.getPageSize());
            dtoPage.setTotalPage(productPage.getTotalPage());
            
            return Result.success(dtoPage);
        } catch (Exception e) {
            return Result.error("查询商品列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取商品详情
     */
    @GetMapping("/{id}")
    public Result<ProductDTO> getProductDetail(@PathVariable Long id) {
        try {
            Product product = productService.getProductDetail(id);
            if (product == null) {
                return Result.error("404", "商品不存在");
            }
            // 更新浏览量
            productService.updateViewCount(id);
            ProductDTO productDTO = productConverter.toDTO(product);
            return Result.success(productDTO);
        } catch (Exception e) {
            return Result.error("获取商品详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增商品
     */
    @PostMapping
    public Result<Boolean> addProduct(@RequestBody ProductDTO productDTO) {
        try {
            Product product = productConverter.toEntity(productDTO);
            boolean result = productService.addProduct(product);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("新增商品失败");
            }
        } catch (Exception e) {
            return Result.error("新增商品失败：" + e.getMessage());
        }
    }

    /**
     * 更新商品
     */
    @PutMapping
    public Result<Boolean> updateProduct(@RequestBody ProductDTO productDTO) {
        try {
            if (productDTO.getId() == null) {
                return Result.error("商品ID不能为空");
            }
            Product product = productConverter.toEntity(productDTO);
            boolean result = productService.updateProduct(product);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("更新商品失败");
            }
        } catch (Exception e) {
            return Result.error("更新商品失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新商品状态
     */
    @PutMapping("/status/batch")
    public Result<Boolean> updateStatusBatch(@RequestParam List<Long> ids, @RequestParam Integer status) {
        try {
            boolean result = productService.updateStatusBatch(ids, status);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("批量更新商品状态失败");
            }
        } catch (Exception e) {
            return Result.error("批量更新商品状态失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新商品价格
     */
    @PutMapping("/price/batch")
    public Result<Boolean> updatePriceBatch(@RequestParam List<Long> ids, @RequestParam Double price) {
        try {
            boolean result = productService.updatePriceBatch(ids, price);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("批量更新商品价格失败");
            }
        } catch (Exception e) {
            return Result.error("批量更新商品价格失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新商品库存
     */
    @PutMapping("/stock/batch")
    public Result<Boolean> updateStockBatch(@RequestParam List<Long> ids, @RequestParam Integer stock) {
        try {
            boolean result = productService.updateStockBatch(ids, stock);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("批量更新商品库存失败");
            }
        } catch (Exception e) {
            return Result.error("批量更新商品库存失败：" + e.getMessage());
        }
    }

    /**
     * 搜索商品
     */
    @GetMapping("/search")
    public Result<PageResult<ProductDTO>> searchProducts(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageResult<Product> productPage = productService.searchProducts(keyword, pageNum, pageSize);
            List<ProductDTO> productDTOs = productConverter.toDTOList(productPage.getList());
            
            PageResult<ProductDTO> dtoPage = new PageResult<>();
            dtoPage.setList(productDTOs);
            dtoPage.setTotal(productPage.getTotal());
            dtoPage.setPageNum(productPage.getPageNum());
            dtoPage.setPageSize(productPage.getPageSize());
            dtoPage.setTotalPage(productPage.getTotalPage());
            
            return Result.success(dtoPage);
        } catch (Exception e) {
            return Result.error("搜索商品失败：" + e.getMessage());
        }
    }

    /**
     * 更新商品收藏量
     */
    @PutMapping("/{id}/favorite")
    public Result<Boolean> updateFavoriteCount(@PathVariable Long id, @RequestParam Integer increment) {
        try {
            boolean result = productService.updateFavoriteCount(id, increment);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("更新商品收藏量失败");
            }
        } catch (Exception e) {
            return Result.error("更新商品收藏量失败：" + e.getMessage());
        }
    }

    /**
     * 删除商品（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteProduct(@PathVariable Long id) {
        try {
            boolean result = productService.deleteProduct(id);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("删除商品失败");
            }
        } catch (Exception e) {
            return Result.error("删除商品失败：" + e.getMessage());
        }
    }

    /**
     * 根据分类ID获取商品数量
     */
    @GetMapping("/count/category/{categoryId}")
    public Result<Integer> countByCategoryId(@PathVariable Long categoryId) {
        try {
            int count = productService.countByCategoryId(categoryId);
            return Result.success(count);
        } catch (Exception e) {
            return Result.error("获取分类商品数量失败：" + e.getMessage());
        }
    }

    /**
     * 根据品牌ID获取商品数量
     */
    @GetMapping("/count/brand/{brandId}")
    public Result<Integer> countByBrandId(@PathVariable Long brandId) {
        try {
            int count = productService.countByBrandId(brandId);
            return Result.success(count);
        } catch (Exception e) {
            return Result.error("获取品牌商品数量失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID列表批量获取商品信息
     */
    @GetMapping("/list")
    public Result<List<ProductDTO>> getProductListByIds(@RequestParam List<Long> ids) {
        try {
            List<Product> products = productService.listByIds(ids);
            List<ProductDTO> productDTOs = productConverter.toDTOList(products);
            return Result.success(productDTOs);
        } catch (Exception e) {
            return Result.error("批量获取商品信息失败：" + e.getMessage());
        }
    }

    /**
     * 根据分类ID获取商品列表
     */
    @GetMapping("/category/{categoryId}")
    public Result<List<ProductDTO>> getProductsByCategoryId(
            @PathVariable Long categoryId,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize) {
        try {
            Map<String, Object> params = new java.util.HashMap<>();
            params.put("categoryId", categoryId);
            params.put("status", 1); // 只查询上架状态的商品
            
            PageResult<Product> productPage = productService.getProductPage(params, 
                    pageNum != null ? pageNum : 1, 
                    pageSize != null ? pageSize : 100);
            
            List<ProductDTO> productDTOs = productConverter.toDTOList(productPage.getList());
            return Result.success(productDTOs);
        } catch (Exception e) {
            return Result.error("获取分类商品列表失败：" + e.getMessage());
        }
    }
}